package ez

import (
	"fmt"
	"gitee.com/dreamwood/ez-go/tools"
	"github.com/nsqio/go-nsq"
	"runtime"
)

// 文件日志
type NsqLogger struct {
	Prefix      string
	TraceDepth  int //跟踪起始深度
	DumpDepth   int //追踪深度
	NsqProducer *nsq.Producer
	Topic       string
}

func NewNsqLogger() *NsqLogger {
	mql := &NsqLogger{
		Prefix:     "[EZ]",
		TraceDepth: 1,
		DumpDepth:  0,
		Topic:      LoggerNsqTopic,
	}
	return mql
}

func (this *NsqLogger) Write(data string) {
	pc, f, l, _ := runtime.Caller(this.TraceDepth)
	data = fmt.Sprintf("%s %s %s:%d FUNC:%s\n%s\n",
		this.Prefix,
		tools.GetDateYMDHIS("-", ":", " "),
		f, l, runtime.FuncForPC(pc).Name(),
		data,
	)
	//添加dump信息
	rightArrow := ""
	for i := 0; i < this.DumpDepth; i++ {
		pc, f, l, _ = runtime.Caller(this.TraceDepth + i + 1)
		if f == "" {
			break
		}
		rightArrow += "→"
		data = fmt.Sprintf("%s %s %s %s:%d FUNC:%s\n",
			this.Prefix,
			tools.GetDateYMDHIS("-", ":", " "),
			rightArrow,
			f, l, runtime.FuncForPC(pc).Name(),
		) + data
	}
	if this.NsqProducer == nil {
		println("NSQLOG连接失败，内容直接打印：", data)
	}
	e := this.NsqProducer.Publish(this.Topic, []byte(data))
	if e != nil {
		println(e)
	}
}
